﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace SystmicFunction.Public.FileService
{
    /// <summary>
    /// 处理Office常见文档Word、Excel
    /// HomePage:http://npoi.codeplex.com/
    /// </summary>
    public static class OfficeHelper
    {
        /// <summary>
        ///   保存office2003格式的Excel
        /// </summary>
        /// <param name="fileName">保存的绝对路径文件名 (office2003 - office2007)</param>
        /// <param name="sheetName">Exl表名</param>
        /// <param name="source">数据源</param>
        /// <param name="attributeNames">要生成的数据源参数名</param>
        public static void SaveExl(String fileName, String sheetName, IEnumerable<Object> source, String[] attributeNames)
        {
            var excel = new HSSFWorkbook();
            ISheet sheet = excel.CreateSheet(sheetName);
            var srcList = source.ToList();//TODO: 数据结构 查询快 定位快 

            for (int i = 0; i < srcList.Count; i++)
            {
                IRow row = sheet.CreateRow(i);
                var data = srcList[i];
                Type objType = data.GetType();
                for (int j = 0; j < attributeNames.Length; j++)
                {
                    PropertyInfo propertyInfo = objType.GetProperty(attributeNames[j]);
                    if (propertyInfo != null)
                    {
                        row.CreateCell(j).SetCellValue(propertyInfo.GetValue(data, null).ToString());
                    }
                }
            }

            /* 写入到客户端  
            using (var ms = new System.IO.MemoryStream())
            {
                book.Write(ms);
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
                Response.BinaryWrite(ms.ToArray());
                book = null;
                ms.Close();
                
            }
            */

            /******
             * 文件流
             * 
             * 
             */
            using (var stream = new FileStream(fileName, FileMode.Create))
            {
                excel.Write(stream);
            }
        }

    }
}
